package com.example.filter;

import com.example.util.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 1. 获取URL
        String url = request.getRequestURL().toString();
        // 2. 判断是否是登录方法
        if (url.contains("login")) {
            log.info("拦截到登录请求，直接放行");
            filterChain.doFilter(request, response);
            return;
        }
        // 3. 获取请求头中的 token
        String token = request.getHeader("token");
        // 4. 判断token是否存在
        if (!StringUtils.hasLength(token)) {
            log.info("令牌长度为空，直接返回401");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return;
        }
        // 5. 解析Token
        try {
            jwtUtil.parseToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回401");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return;
        }

        // 6. 放行
        log.info("令牌校验成功，放行");
        filterChain.doFilter(request, response);
    }

}
